package com.hawthorn.redis.service.role.impl;

import com.hawthorn.component.constant.RedisConstant;
import com.hawthorn.component.utils.common.StrMyUtil;
import com.hawthorn.entity.dto.SysUserRoleDTO;
import com.hawthorn.platform.redis.RedisMyClient;
import com.hawthorn.redis.repository.UserRoleCacheMapper;
import com.hawthorn.redis.service.role.UserRoleCacheService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

/**
 * <p>todo 加载用户角色关系缓存服务实现类 </p>
 * @author: andyten@tom.com | xukaixing@hotmail.com
 * @created: 2021/11/26 12:32 PM
 * @version v1.0.1
 * @copyright: Copyright (c)  andyten
 */
@Service
@Slf4j
public class UserRoleCacheServiceImpl implements UserRoleCacheService
{
  @Resource
  RedisMyClient redisMyClient;

  @Resource
  private UserRoleCacheMapper userRoleCacheMapper;

  @Transactional(readOnly = true)
  public void init()
  {

    List<SysUserRoleDTO> userRoleCache = userRoleCacheMapper.selectUserRole();
    String key;
    // todo 先删除redis中的key
    redisMyClient.removeAll(StrMyUtil.placeHolder(RedisConstant.REDIS_KEY_USERROLE_PREFIX, "*"));
    String userRoles = "";
    for (SysUserRoleDTO sysUserRoleDTO : userRoleCache)
    {
      key = StrMyUtil.placeHolder(RedisConstant.REDIS_KEY_USERROLE_PREFIX, sysUserRoleDTO.getUserAccount());
      String tempValue = redisMyClient.get(key);
      if ("".equals(tempValue))
      {
        userRoles = String.valueOf(sysUserRoleDTO.getRoleId());
      } else
      {
        userRoles += ":" + sysUserRoleDTO.getRoleId();
      }
      redisMyClient.set(key, userRoles);
    }
    log.info("====== load userrole data to redis success ======");
  }
}
